//跟进计划列表
var $customerPayFromTable = $('#customerPayFrom');
var abs = new verjs_select();
// 表格高度
var globalHeight;


//防止表头与表格不对齐
$(window).resize(function () {
    $customerPayFromTable.bootstrapTable('resetView');
});

$(function () {
    globalHeight = $(window).height() - $('#customerPayFrom').offset().top - 60 - 24;
    //初始化列表
    customerPayFromList();
    //分公司财务隐藏公司列
    if ($("#deptIdHide").val() == 3){
        $customerPayFromTable.bootstrapTable('showColumn', "companyName");
    }

    $('#addInputMoney').on('show.bs.modal', function () {
        $(this).find('.modal-dialog').draggable();
    });

    $('#arriveTime').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd",
        endDate: new Date(),
    });
    loadCompanyList();
    loadAllCompanyList();
    isSuperCaiwu()
    $("#payStatus").selectpicker()

})


//判断是否隐藏所属分公司
function isSuperCaiwu(){
    $.ajax({
        type: 'GET',
        dataType: "json",
        url: '/order/isSuperCaiwu',
        cache : false,
        async : false,
        success: (function (data) {
            if (!data.data) {
                document.getElementById("companySelectDiv").style.display="none";

            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/**
 * 功能：缩放页面重绘table高度
 * */
$(window).resize(debounce(resizeTable, 500));
function resizeTable() {
    // 计算初始表格高度 = 浏览器高度 - 表格距浏览器顶部高度 - 主体底部padding+margin
    // 注：表格距浏览器顶部高度此处用最外层div获取，解决table垂直滚动时距离
    globalHeight = $(window).height() - $('.bootstrap-table').offset().top - 60 - 24;
    $('#customerPayFrom').bootstrapTable('resetView', {height: globalHeight});
}

function loadAllCompanyList() {
    $.getJSON("/sysCompany/selectCompanies ", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">请选择</option>';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $("#companySelect").html("");
            $('#companySelect').append(companyOptionHtml);
            $('#companySelect').selectpicker('refresh');
        }
    });
}

function customerPayFromList() {
//先销毁表格
    $customerPayFromTable.bootstrapTable('destroy');
    $customerPayFromTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: '/customerPay/selectCustomerPayList',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        height: globalHeight,
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'customerPayId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', formatter: indexFormat},
            {title: '客户名称',field: 'customerName', align: 'left', valign: 'middle'},
            {title: '充值金额',field: 'payMoney', align: 'left', valign: 'middle',sortable: true,},
            {title: '充值码',field: 'payNumber', align: 'left', valign: 'middle'},
            {title: '充值类型', field: 'payType', align: 'left', valign: 'middle',formatter: payTypeFormat},
            {title: '充值状态', field: 'payStatus', align: 'left', valign: 'middle',formatter: payStatusFormat,sortable: true,},
            {title: '申请人', field: 'createPeopleName', align: 'left', valign: 'middle',sortable: true,},
            {title: '所属公司', field: 'companyName', align: 'left', valign: 'middle', visible: false,sortable: true,},
            {title: '申请时间', field: 'createTm', sortable: true,align: 'left', valign: 'middle'},
            {title: '到款日期', field: 'paymentDate', sortable: true,align: 'left', valign: 'middle'},
            {title: '审批人', field: 'financeName', sortable: true,align: 'left', valign: 'middle'},
            {title: '操作',field: 'operate',align: 'left',formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#taxDiscFrom').css({
                minWidth: $('#taxDiscFrom').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0,11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}


function searchOrderList(type) {
    if(type == 1){
        $('.all').addClass('active-second');
        $('.today').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.year').removeClass('active-second');
        $("#dateType").val("all");
        $customerPayFromTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }else{
        $customerPayFromTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: advancedQueryParams});
    }

}

function queryParams(params){
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.dataType = 1;//充值类型查询普通充值的
    params.dateType = $("#dateType").val();
    return params;
}

function advancedQueryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.dataType = 1;//充值类型查询普通充值的
    params.dateType = $("#dateType").val();

    params.arriveTimeStart = $('#arriveTimeStart').val();//到款开始时间
    params.arriveTimeEnd = $('#arriveTimeEnd').val();//到款结束时间
    params.arriveMoneyStart = $('#arriveMoneyStart').val();//到款起始金额
    params.arriveMoneyEnd = $('#arriveMoneyEnd').val();//到款截止金额
    params.salesmanName = $('#applicationName').val();//申请人
    params.createPeopleName = $('#inputName').val();//录入人
    params.paymentAccount = $('#paymentAccountNum').val(); //付款账号
    params.companyId = $('#companySelect').val();  //公司id
    params.payStatus = $('#payStatus').val();  //充值状态
    return params;
}

function indexFormat(value, row, index) {
    return index + 1;
}


/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    if(row.payStatus == 1){
        let html = '';
        //customerName
        html += '<button  class="btn btn-default" ' +
            'onclick="details(\''+row.customerPayId+'\')">查看</button>'
        html += '</ul></div>'
        return html;
    }else{
        let html = '';
        //customerName
        html += '<button class="btn btn-default" data-toggle="collapse" data-target="#updatePay" aria-expanded="false" aria-controls="updatePay" ' +
            'onclick="notarizePay(\''+row.customerPayId+'\',\''+row.payStatus+'\',\''+row.customerName+'\',\''+row.payMoney+'\',\''+row.customerId+'\')">查看</button>';
        html += '</ul></div>'
        return html;
    }
}

function  details(id) {
    $.ajax({
        type: "get",
        url: "/customerPay/queryCustomerPayDetail",
        data: {
            customerPayId: id
        },
        dataType: 'json',
        success: (function (data) {
            if (data.code == "000000") {
                $('#paymentNum').text(data.data.paymentAccount);
                $('#paymentCompany').text(data.data.paymentUnit);
                $('#payNumber').text(data.data.payNumber);
                $('#paymentDate').text(data.data.paymentDate);
                $('#payMoney').text(data.data.payMoney);
                $('#arriveUnitName').text(data.data.arriveUnitName);
                $('#createPeopleName').text(data.data.createPeopleName);
                $('#createTime').text(data.data.createTm);
                $('#paymentSerial').text(data.data.paymentSerial);
                $('#checkDetails').modal('show')
            } else {
                $.alert(data.message);
            }
        }),
        error: (function (res) {
            $.alert('操作失败，请稍后再试!');
        })
    });
}


//回显
function notarizePay(customerPayId,payStatus,customerName,payMoney,customerId) {
    $.alert("该条充值记录未到账，不能查看");
    // if (payStatus == 1){
    //     $.alert("该条充值信息财务已经确认收款");
    //     return;
    // }
    // $("#paymentUnit").val(customerName)
    // $('#customerPayIdHide').val(customerPayId);
    // $('#addInputMoney').modal('show');
    // $('#payMoneyIdHide').val(payMoney);
    // $('#customerId').val(customerId);
    /*$.alert({
        title: '提示',
        content: '您确认收到该客户充值转账了吗？',
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary',
                action: function () {
                    $.ajax({
                        type: "post",
                        url: "/customerPay/notarizeCustomerPay",
                        data: {
                            customerPayId: customerPayId
                        },
                        dataType: 'json',
                        success: (function (data) {
                            if (data.code == "000000") {
                                $.alert({
                                    title: '提示',
                                    content: '操作成功！',
                                    buttons: {
                                        confirm: {
                                            text: '确认',
                                            btnClass: 'btn-primary',
                                            action: function () {
                                                window.location.reload();
                                            }
                                        }
                                    }
                                });
                            } else {
                                $.alert(data.message);
                            }
                        }),
                        error: (function (res) {
                            $.alert('操作失败，请稍后再试!');
                        })
                    });
                }
            }
        }
    });*/
}

function inputMoney(element) {

    var paymentUnit = $.trim($('#paymentUnit').val());//付款单位
    var paymentAccount = $.trim($('#paymentAccount').val());//付款账号
    var arriveMethod = $.trim($('#arriveMethod').val());//到款方式
    var paymentSerial = $.trim($('#serial').val());//流水号
    var paymentBank = $.trim($('#paymentBank').val());//付款银行
    var arriveAccountType = $.trim($('#arriveAccountType').val());//到款账号类型
    var remark = $.trim($('#remark').val());//备注
    var chsCustomerPayId = $.trim($('#customerPayIdHide').val());//主键
    var arriveUnitName = $("#arriveAccountType").find("option:selected").text();
    var paymentDate = $('#arriveTime').val();
    var payMoney = $("#arriveMoney").val();
    var customerId = $("#customerId").val();

    // if (!paymentUnit) {
    //     promptInfo("付款单位不能为空!");
    //     return;
    // }
    // if (!arriveMethod) {
    //     promptInfo("到款方式不能为空!");
    //     return;
    // }
    // if (arriveMethod == 0) {
    //     if (!paymentBank){
    //         promptInfo("付款银行不能为空!");
    //         return;
    //     }
    //     if (!serial){
    //         promptInfo("流水号不能为空!");
    //         return;
    //     }
    //     if (!paymentAccount) {
    //         promptInfo("付款账号不能为空!");
    //         return;
    //     }
    // }
    // if (!arriveAccountType) {
    //     promptInfo("到款账号类型不能为空!");
    //     return;
    // }
    if($("#payMoneyIdHide").val() != $("#arriveMoney").val()){
        promptInfo("到款金额与申请金额不一致，不能确认收款!");
        return;
    }
    $('.form-pay').bootstrapValidator({
        fields: {
            paymentUnit: {
                validators: {
                    notEmpty: {
                        message: '付款单位不能为空'
                    },

                }
            },
            arriveMethod: {
                validators: {
                    notEmpty: {
                        message: '到款方式不能为空'
                    }
                }
            },
            arriveAccountType: {
                validators: {
                    notEmpty: {
                        message: '到款账号类型不能为空'
                    }
                }
            },
            arriveTime:{
                trigger:"change",
                validators: {
                    notEmpty: {
                        message: '到款时间不能为空'
                    }
                }
            }
        },
    })
    $(".form-pay").bootstrapValidator('validate');//提交验证
    if (!$(".form-pay").data('bootstrapValidator').isValid()) {//获取验证结果，如果成功，执行下面代码

        return;
    }
    $(element).prop('disabled', true);

    if(chsCustomerPayId != null || chsCustomerPayId != ""){
        //新增回款
        var jsonData = {
            "chsCustomerPayId":chsCustomerPayId,
            "paymentUnit":paymentUnit,
            "paymentAccount":paymentAccount,
            "arriveMethod":arriveMethod,
            "arriveAccountType":arriveAccountType,
            "remark":remark,
            "paymentSerial":paymentSerial,
            "paymentBank":paymentBank,
            "arriveUnitName":arriveUnitName,
            "paymentDate":paymentDate,
            "payMoney":payMoney,
            "customerId":customerId,
            "payType":1
        }


        $.ajax({
            url: '/customerPay/notarizeCustomerPay',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if(data.code == '000000'){
                    $.alert({
                        title: '提示',
                        content: '操作成功！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    //页面跳转赋值
                                    var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                    var navTab = parent.$multitabs._getNavTab($thisTabs);
                                    window.location.reload();
                                    /*closeTab(navTab);
                                    openTab("回款记录","/front/receiptManager/userReceiptRecord");*/
                                    //delStorageAndRemove(navTab);
                                }
                            }
                        }
                    });
                }else {
                    $.alert(data.message);
                }
            }),
            error: (function (res) {
                $.alert("操作失败");
            })
        })
    }
}

/**
 * 加载回款公司信息
 */
function loadCompanyList() {
    var companyOptionHtml = '<option value="">请选择</option>';
    var trueCompanyName = $("#companyNameId").val();
    if (trueCompanyName && trueCompanyName != "北京财税研究院" && trueCompanyName !="大成方略网络科技有限公司" && trueCompanyName !="北京大成方略财务顾问有限公司"
        && trueCompanyName != "北京大成方略纳税人俱乐部有限公司" && trueCompanyName !="大成方略纳税人俱乐部股份有限公司"){
        companyOptionHtml += '<option value="0">' + trueCompanyName + '</option>';
    }
    companyOptionHtml += '<option value="1">北京财税研究院</option>';
    companyOptionHtml += '<option value="2">大成方略网络科技有限公司</option>';
    companyOptionHtml += '<option value="3">北京大成方略财务顾问有限公司</option>';
    companyOptionHtml += '<option value="4">北京大成方略纳税人俱乐部有限公司</option>';
    companyOptionHtml += '<option value="5">大成方略纳税人俱乐部股份有限公司</option>';
    $('#arriveAccountType').html("");
    $('#arriveAccountType').append(companyOptionHtml);
    $('#arriveAccountType').selectpicker('refresh');
}

function clearAllData() {
    window.location.reload();
}

function payTypeFormat(value, row, index) {
    var html = "";
    if (value == 1){
        html = "普通充值";
    }
    if (value == 2){
        html = "转入额";
    }
    return html;
}

function payStatusFormat(value, row, index) {
    var html = "";
    if (value == 0){
        html = "充值中";
    }
    if (value == 1){
        html = "已到账";
    }
    return html;
}

/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    if (time == 'today') {//今天
        $('.today').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisToday");
    }
    $customerPayFromTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

function hideInput() {
    // window.location.reload();
    $("#paymentUnit").val('')
    $("#arriveMethod").val('0')
    $("#arriveAccountType").val('')
    $("#arriveMoney").val('')
    if($(".form-pay").data('bootstrapValidator')!=undefined){
        $(".form-pay").data('bootstrapValidator').destroy();
        $('.form-pay').data('bootstrapValidator', null);
    }
}



$('#myButton').on('click', function () {
    var $btn = $(this).button('loading');

    var paramsData = {
        customerName : $.trim($('#customerName').val()),//客户名称
        dataType : 1,//充值类型查询普通充值的
        dateType : $.trim($('#dateType').val()),//合同编号
        arriveTimeStart : $.trim($('#arriveTimeStart').val()),//到款开始时间
        arriveTimeEnd : $.trim($('#arriveTimeEnd').val()),//到款结束时间
        arriveMoneyStart : $.trim($('#arriveMoneyStart').val()),//到款起始金额
        arriveMoneyEnd : $.trim($('#arriveMoneyEnd').val()),//到款截止金额
        salesmanName : $.trim($('#applicationName').val()),//申请人
        createPeopleName : $.trim($('#inputName').val()),//录入人
        paymentAccount : $.trim($('#paymentAccountNum').val()),//付款账号
        companyId : $.trim($('#companySelect').val()),//到款金额起

    }
    // json转url参数
    var parseParam = function(param, key) {
        var paramStr = '';
        if (param instanceof String || param instanceof Number || param instanceof Boolean) {
            paramStr += '&' + key + '=' + param;
        } else {
            $.each(param, function(i) {
                var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i);
                paramStr += '&' + parseParam(this, k);
            });
        }
        return paramStr.substr(1);
    };
    var that = this;
    paramsData = parseParam(paramsData);
    var page_url = '/customerPay/exportCustomerPayList?'+paramsData;
    var req = new XMLHttpRequest();
    req.open("get", page_url, true);
    req.responseType = "blob";
    req.onreadystatechange = function () {
        if (req.readyState === 4 && req.status === 200) {
            // var filename = $(that).data('filename');
            if (typeof window.chrome !== 'undefined') {
                // Chrome version
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(req.response);
                link.download = '客户充值.xlsx';
                link.click();
            } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE version
                var blob = new Blob([req.response], { type: 'application/force-download' });
                window.navigator.msSaveBlob(blob, '回款统计.xlsx');
            } else {
                // Firefox version
                var file = new File([req.response], '回款统计.xlsx', { type: 'application/force-download' });
                window.open(URL.createObjectURL(file));
            }
            $btn.button('toggle');
            $btn.button('reset');
        }
    };
    req.send();
})


function clearAllData(){
    $('#arriveTimeStart').val('')
    $('#arriveTimeEnd').val('')
    $('#arriveMoneyStart').val('')
    $('#arriveMoneyEnd').val('')
    $('#applicationName').val('')
    $('#inputName').val('')
    $('#paymentAccountNum').val('')
    $('#createName').val('')
    $('#payStatus').val('').selectpicker('refresh');
    $('#companySelect').val('').selectpicker('refresh');
    $customerPayFromTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
}